<template>
  <!-- 创建这个页面的目的主要是用来方便调用下拉刷新和上拉加载的组件 -->
  <div class="article-list" @scroll="scrollEvent" ref="articleList">
    <van-pull-refresh v-model="isLoading" @refresh="refresh">
      <van-list
        v-if="bol"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多数据了"
        @load="getData"
      >
        <article-item :item="i" v-for="i in list" :key="i.art_id" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from './article-item.vue'
import { articlesGet } from '@/api/home.js'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  data () {
    return {
      bol: true, // 用于静默刷新
      isLoading: false, // 页面是否在刷新中，下拉时会触发使转换成true
      loading: false, // 是否处于加载中,当滚动条距离底部小于300时触发使转换成true
      finished: false, // 是否完成加载
      list: [],
      timestamp: Date.now(), // 时间戳
      scrollTop: 0 //储存滚动位置的值
    }
  },
  props: ['id'],
  created () {
    // this.getData()
  },
  methods: {
    async getData () {
      const res = await articlesGet({
        channel_id: this.id,
        timestamp: this.timestamp
      })
      // console.log(res)
      // 数据累加处理
      this.list.push(...res.data.results)
      // loading改为false
      this.loading = false
      if (res.data.pre_timestamp) {
        //有时间戳就说明有下一页，储存时间戳
        this.timestamp = res.data.pre_timestamp
      } else {
        //没有时间戳，加载完成
        this.finished = true
      }
    },
    // 下拉刷新
    async refresh () {
      // list组件的属性还原
      this.loading = false
      this.finished = false
      // 调用第一页数据，时间戳还原
      //   this.timestamp = Date.now()
      //   this.list = []
      // 调用刷新接口
      //   await this.getData()
      // 调用成功后停止刷新
      this.isLoading = false
      // 将组件初始化一次
      // 静默刷新，文章列表重新渲染，会自动调用getData方法
      this.bol = false
      this.$nextTick(() => {
        this.bol = true
      })
    },
    // 滚动条滚动事件
    scrollEvent () {
      this.scrollTop = this.$refs.articleList.scrollTop
    },

    deactivated () {}
  },
  // 激活组件
  activated () {
    this.$refs.articleList.scrollTop = this.scrollTop
  }
}
</script>
<style scoped lang="less">
.article-list {
  height: 100%;
  overflow-y: auto;
  padding: 0 16px;
}
</style>
